<?php

class CommentModel
{
    private $commentKeyPrefix   =   'CI/';
    private $commentMeType      =   1;
    private $meCommentType      =   2;
    private $userCommentMeType  =   3;
    private $autoUidModel;
    private $topicModel;
    private $attachmentModel;
    private $diaryListCacheModel;
    private $childCommentModel;
    private $slaveKey           =   '/slave';
    
    function __construct()
    {
        $this->autoUidModel         =   new AutoUidModel();
        $this->topicModel           =   new TopicModel();
        $this->attachmentModel      =   new AttachmentModel();
        $this->diaryListCacheModel  =   new DiaryListCacheModel();
        $this->childCommentModel    =   new ChildCommentModel();
    }

    public function getCommentInfo($info)/*{{{*/
    {
        if (empty($info['uid']) ||  empty($info['bodyId'])  ||  empty($info['type']))
        {
            AC::$errorNo    =   'CIM006';
            return  FALSE;
        }

        $start  =   0;
        $length =   AC::COMMENT_LIST_DISPLAY_LEN;
        isset($info['start'])   &&  $start  =   $info['start'];
        isset($info['length'])  &&  $length =   $info['length'];
        if ($start  <   0)  $start  =   0;

        $key    =   $this->commentKeyPrefix. $info['uid'];
        $where  =   array('bodyId'  =>  $info['bodyId'], 'type' => $info['type'], 'commentType' => $this->commentMeType);
        $orderBy=   ' id DESC ';
        $result =   Storage::getConditionManyData($key, $where, $orderBy, $start, $length);
        return  $result;
    }/*}}}*/

    public function getCommentTop($info)/*{{{*/
    {
        if (empty($info['uid']) ||  empty($info['bodyId'])  ||  empty($info['type']))
        {
            AC::$errorNo    =   'CIM006';
            return  FALSE;
        }

        $start  =   0;
        $length =   AC::COMMENT_LIST_DISPLAY_LEN;
        isset($info['start'])   &&  $start  =   $info['start'];
        isset($info['length'])  &&  $length =   $info['length'];
        if ($start  <   0)  $start  =   0;

        $key    =   $this->commentKeyPrefix. $info['uid'];
        $where  =   array('bodyId'  =>  $info['bodyId'], 'type' => $info['type'], 'commentType' => $this->commentMeType, 'parentId' => 0);
        $orderBy=   ' id DESC ';
        $result =   Storage::getConditionManyData($key, $where, $orderBy, $start, $length);

        if (empty($result)  ||  !is_array($result)) return  $result;
        foreach ($result    as  &$commentInfo)
        {
            if (empty($commentInfo['id']))  continue;

            $info['parentId']           =   $commentInfo['id'];
            $commentInfo['replyList']   =   $this->getCommentReplyList($info);
            
            unset($commentInfo['extra']);
            if ($commentInfo['replyList']) {
                foreach ($commentInfo['replyList'] as &$val) {
                    unset($val['extra']);
                }
            }
        }
        return  $result;
    }/*}}}*/

    public function getCommentInfoList($info)/*{{{*/
    {
        if(empty($info['type'])){
            $info['type'] = 1;
        }
        if (empty($info['uid']) ||  empty($info['bodyId'])  ||  empty($info['type']))
        {
            AC::$errorNo    =   'CIM006';
            return  FALSE;
        }

        $start  =   0;
        $length =   AC::COMMENT_LIST_DISPLAY_LEN;
        isset($info['start'])   &&  $start  =   $info['start'];
        isset($info['length'])  &&  $length =   $info['length'];
        if ($start  <   0)  $start  =   0;

        $key    =   $this->commentKeyPrefix. $info['uid'].$this->slaveKey;
        $where  =   array('bodyId'  =>  $info['bodyId'], 'type' => $info['type'], 'commentType' => $this->commentMeType, 'parentId' => 0);
        if (!empty($info['id']))    $where  =   ' id > '. $info['id']. ' AND bodyId = '. $info['bodyId']. ' AND `commentType` = '. $this->commentMeType. ' AND parentId = 0';
        $orderBy=   ' id DESC ';
        $result =   Storage::getConditionManyData($key, $where, $orderBy, $start, $length);

        if (empty($result)  ||  !is_array($result)) return  $result;
        foreach ($result    as  &$commentInfo)
        {
            if (empty($commentInfo['id']))  continue;

            $info['parentId']           =   $commentInfo['id'];
            $commentInfo['replyList']   =   $this->getCommentReplyList($info);
        }
        return  $result;
    }/*}}}*/
    public function getCommentInfoListUp($info)/*{{{*/
    {
    	if(empty($info['type'])){
    		$info['type'] = 1;
    	}
        if (empty($info['uid']) ||  empty($info['bodyId'])  ||  empty($info['type']))
        {
            AC::$errorNo    =   'CIM006';
            return  FALSE;
        }
        if (empty($info['id'])) return  $this->getCommentInfoList($info);

        $start  =   0;
        $length =   AC::COMMENT_LIST_DISPLAY_LEN;
        isset($info['start'])   &&  $start  =   $info['start'];
        isset($info['length'])  &&  $length =   $info['length'];
        if ($start  <   0)  $start  =   0;

        $key    =   $this->commentKeyPrefix. $info['uid'].$this->slaveKey;
        $where  =   ' id > '. $info['id']. ' AND bodyId = '. $info['bodyId']. ' AND `commentType` = '. $this->commentMeType. ' AND parentId = 0';
        $orderBy=   ' id ASC ';
        $result =   Storage::getConditionManyData($key, $where, $orderBy, $start, $length);

        if (empty($result)  ||  !is_array($result)) return  $result;
        foreach ($result    as  &$commentInfo)
        {
            if (empty($commentInfo['id']))  continue;

            $info['parentId']           =   $commentInfo['id'];
            $commentInfo['replyList']   =   $this->getCommentReplyList($info);
        }
        return  $result;
    }/*}}}*/
    public function getCommentInfoListDown($info)/*{{{*/
    {
    	if(empty($info['type'])){
    		$info['type'] = 1;
    	}
        if (empty($info['uid']) ||  empty($info['bodyId'])  ||  empty($info['type']))
        {
            AC::$errorNo    =   'CIM006';
            return  FALSE;
        }
        if (empty($info['id'])) return  $this->getCommentInfoList($info);

        $start  =   0;
        $length =   AC::COMMENT_LIST_DISPLAY_LEN;
        isset($info['start'])   &&  $start  =   $info['start'];
        isset($info['length'])  &&  $length =   $info['length'];
        if ($start  <   0)  $start  =   0;

        $key    =   $this->commentKeyPrefix. $info['uid'].$this->slaveKey;
        $where  =   ' id < '. $info['id']. ' AND bodyId = '. $info['bodyId']. ' AND `commentType` = '. $this->commentMeType. ' AND parentId = 0';
        $orderBy=   ' id DESC ';
        $result =   Storage::getConditionManyData($key, $where, $orderBy, $start, $length);

        if (empty($result)  ||  !is_array($result)) return  $result;
        foreach ($result    as  &$commentInfo)
        {
            if (empty($commentInfo['id']))  continue;

            $info['parentId']           =   $commentInfo['id'];
            $commentInfo['replyList']   =   $this->getCommentReplyList($info);
        }
        return  $result;
    }/*}}}*/

    public function getCommentMeList($info)/*{{{*/
    {
        if (empty($info['uid']))
        {
            AC::$errorNo    =   'CIM007';
            return  FALSE;
        }

        $start  =   0;
        $length =   AC::COMMENT_LIST_DISPLAY_LEN;
        isset($info['start'])   &&  $start  =   $info['start'];
        isset($info['length'])  &&  $length =   $info['length'];
        if ($start  <   0)  $start  =   0;

        $key    =   $this->commentKeyPrefix. $info['uid'].$this->slaveKey;
        $where  =   array('commentType' => $this->commentMeType);
        if (!empty($info['id']))    $where  =   ' id < '. $info['id']. ' AND `commentType` = '. $this->commentMeType. ' ';
        $orderBy=   ' id DESC ';
        $result =   Storage::getConditionManyData($key, $where, $orderBy, $start, $length);
        return  $result;
    }/*}}}*/
    public function getCommentMeListUp($info)/*{{{*/
    {
        if (empty($info['uid']))
        {
            AC::$errorNo    =   'CIM007';
            return  FALSE;
        }
        if (empty($info['id'])) return  $this->getCommentMeList($info);

        $start  =   0;
        $length =   AC::COMMENT_LIST_DISPLAY_LEN;
        isset($info['start'])   &&  $start  =   $info['start'];
        isset($info['length'])  &&  $length =   $info['length'];
        if ($start  <   0)  $start  =   0;

        $key    =   $this->commentKeyPrefix. $info['uid'].$this->slaveKey;
        $where  =   ' id > '. $info['id']. ' AND `commentType` = '. $this->commentMeType. ' ';
        $orderBy=   ' id ASC ';
        $result =   Storage::getConditionManyData($key, $where, $orderBy, $start, $length);
        return  $result;
    }/*}}}*/
    public function getCommentMeListDown($info)/*{{{*/
    {
        if (empty($info['uid']))
        {
            AC::$errorNo    =   'CIM007';
            return  FALSE;
        }
        if (empty($info['id'])) return  $this->getCommentMeList($info);

        $start  =   0;
        $length =   AC::COMMENT_LIST_DISPLAY_LEN;
        isset($info['start'])   &&  $start  =   $info['start'];
        isset($info['length'])  &&  $length =   $info['length'];
        if ($start  <   0)  $start  =   0;

        $key    =   $this->commentKeyPrefix. $info['uid'].$this->slaveKey;
        $where  =   ' id < '. $info['id']. ' AND `commentType` = '. $this->commentMeType. ' ';
        $orderBy=   ' id DESC ';
        $result =   Storage::getConditionManyData($key, $where, $orderBy, $start, $length);
        return  $result;
    }/*}}}*/

    public function getMeCommentList($info)/*{{{*/
    {
        if (empty($info['uid']))
        {
            AC::$errorNo    =   'CIM008';
            return  FALSE;
        }

        $start  =   0;
        $length =   AC::COMMENT_LIST_DISPLAY_LEN;
        isset($info['start'])   &&  $start  =   $info['start'];
        isset($info['length'])  &&  $length =   $info['length'];
        if ($start  <   0)  $start  =   0;

        $key    =   $this->commentKeyPrefix. $info['uid'].$this->slaveKey;
        $where  =   array('commentType' => $this->meCommentType);
        if (!empty($info['id']))    $where  =   ' id > '. $info['id']. ' AND `commentType` = '. $this->meCommentType. ' ';
        $orderBy=   ' id DESC ';
        $result =   Storage::getConditionManyData($key, $where, $orderBy, $start, $length);
        return  $result;
    }/*}}}*/
    public function getMeCommentListUp($info)/*{{{*/
    {
        if (empty($info['uid']))
        {
            AC::$errorNo    =   'CIM008';
            return  FALSE;
        }
        if (empty($info['id'])) return  $this->getMeCommentList($info);

        $start  =   0;
        $length =   AC::COMMENT_LIST_DISPLAY_LEN;
        isset($info['start'])   &&  $start  =   $info['start'];
        isset($info['length'])  &&  $length =   $info['length'];
        if ($start  <   0)  $start  =   0;

        $key    =   $this->commentKeyPrefix. $info['uid'].$this->slaveKey;
        $where  =   ' id > '. $info['id']. ' AND `commentType` = '. $this->meCommentType. ' ';
        $orderBy=   ' id ASC ';
        $result =   Storage::getConditionManyData($key, $where, $orderBy, $start, $length);
        return  $result;
    }/*}}}*/
    public function getMeCommentListDown($info)/*{{{*/
    {
        if (empty($info['uid']))
        {
            AC::$errorNo    =   'CIM008';
            return  FALSE;
        }
        if (empty($info['id'])) return  $this->getMeCommentList($info);

        $start  =   0;
        $length =   AC::COMMENT_LIST_DISPLAY_LEN;
        isset($info['start'])   &&  $start  =   $info['start'];
        isset($info['length'])  &&  $length =   $info['length'];
        if ($start  <   0)  $start  =   0;

        $key    =   $this->commentKeyPrefix. $info['uid'].$this->slaveKey;
        $where  =   ' id < '. $info['id']. ' AND `commentType` = '. $this->meCommentType. ' ';
        $orderBy=   ' id DESC ';
        $result =   Storage::getConditionManyData($key, $where, $orderBy, $start, $length);
        return  $result;
    }/*}}}*/
    // 获取我评论的列表
    public function getMeCommen($info)/*{{{*/
    {
        if (empty($info['uid']))
        {
            AC::$errorNo    =   'CIM008';
            return  FALSE;
        }
    
        $start  =   0;
        $length =   AC::COMMENT_LIST_DISPLAY_LEN;
        isset($info['length'])  &&  $length =   $info['length'];
    
        $key    =   $this->commentKeyPrefix. $info['uid'].$this->slaveKey;
        $where  =   array('commentType'=>$this->meCommentType);
        if(intval($info['id']) > 0){
            $where  =   ' id < '. $info['id']. ' AND `commentType` = '. $this->meCommentType. ' ';
        }
        $orderBy=   ' id DESC ';
        $result =   Storage::getConditionManyData($key, $where, $orderBy, $start, $length);
        return  $result;
    }/*}}}*/
    
    // 获取评论我的列表
    public function getCommenMe($info)/*{{{*/
    {
        if (empty($info['uid']))
        {
            AC::$errorNo    =   'CIM008';
            return  FALSE;
        }
    
        $start  =   0;
        $length =   AC::COMMENT_LIST_DISPLAY_LEN;
        isset($info['length'])  &&  $length =   $info['length'];
    
        $key    =   $this->commentKeyPrefix. $info['uid'].$this->slaveKey;
        $where  =   ' uid = '.$info['uid'].'   AND (`commentType` = '. $this->commentMeType. ' OR commentType = '.$this->userCommentMeType.')';
        if(intval($info['id']) > 0){
            $where  =   ' id < '. $info['id']. ' AND  uid = '.$info['uid'].' AND (`commentType` = '. $this->commentMeType. ' OR commentType = '.$this->userCommentMeType.')';
        }
        $orderBy=   ' id DESC ';
        $result =   Storage::getConditionManyData($key, $where, $orderBy, $start, $length);
        return  $result;
    }/*}}}*/
    
    public function postComment($info)/*{{{*/
    {
    	$info['content'] = UK::getstr($info['content'], AC::COMMECT_DATA_NUMBERS);
    	$info['nickname'] = UK::getstr($info['nickname'], 24,'',1);
    	$info['cNickname'] = UK::getstr($info['cNickname'], 24,'',1);
    	
        if (empty($info['uid']) ||  strlen($info['nickname']) < 1||  empty($info['cUid'])    ||  strlen($info['cNickname']) <1)
        {
            AC::$errorNo    =   'CIM001';
            return  FALSE;
        }
        if (empty($info['type']) ||  empty($info['bodyId']) || strlen($info['content']) < 1)
        {
            AC::$errorNo    =   'CIM002';
            return  FALSE;
        }

        if (AC::FEED_COMMENT == $info['type'])
        {
            AC::$errorNo    =   'CIM009';
            return  FALSE;
        }
        if (!empty($info['parentId']))
        {
            $replyInfo      =   array('uid' => $info['cUid'], 'id' => $info['parentId']);
            $oneComment     =   $this->getOneComment($replyInfo);
            if (empty($oneComment['uid']))
            {
                AC::$errorNo=   'CIM012';
                return  FALSE;
            }
        }
        
        #   post MeComment  /*{{{*/
        $dataMeComment  =   array(
                                'uid'           =>  $info['uid'],
                                'cUid'          =>  $info['cUid'],
                                'cNickname'     =>  $info['cNickname'],
                                'rUid'          =>  $info['rUid'],
                                'rNickname'     =>  $info['rNickname'],
                                'bodyId'        =>  $info['bodyId'],
                                'parentId'      =>  $info['parentId'],
                                'type'          =>  $info['type'],
                                'content'       =>  $info['content'],
                                'commentType'   =>  $this->meCommentType,
                                'time'          =>  AC::SERVER_TIME,
                                'replyTime'     =>  AC::SERVER_TIME,
                            );
        $meCommentKey   =   $this->commentKeyPrefix. $info['uid'];
        $meCommentResult=   Storage::addData($meCommentKey, $dataMeComment);
        if (empty($meCommentResult))
        {
            AC::$errorNo    =   'CIM003';
            return  FALSE;
        }/*}}}*/
        // 二级评论时往被评论人插入一个type为3的数据
        // 标记为二级评论
        // 如果被评论人是当前帖子主人则不添加
        if (intval($info['rUid']) > 0 && $info['cUid'] != $info['rUid']){
            #   post Other  /*{{{*/
            $dataUserCommentMe  =   array(
                                'uid'           =>  $info['rUid'],
                                'cUid'          =>  $info['uid'],
                                'cNickname'     =>  $info['nickname'],
                                'rUid'          =>  $info['rUid'],
                                'rNickname'     =>  $info['rNickname'],
                                'bodyId'        =>  $info['bodyId'],
                                'parentId'      =>  $info['parentId'],
                                'type'          =>  $info['type'],
                                'content'       =>  $info['content'],
                                'commentType'   =>  $this->userCommentMeType,
                                'time'          =>  AC::SERVER_TIME,
                                'replyTime'     =>  AC::SERVER_TIME,
                            );
            $userCommentMeKey   =   $this->commentKeyPrefix. $info['rUid'];
            $userCommentMeResult=   Storage::addData($userCommentMeKey, $dataUserCommentMe);
            if (empty($userCommentMeResult))
            {
                AC::$errorNo    =   'CIM005';
                return  FALSE;
            }/*}}}*/
        }

        #   post CommentMe  /*{{{*/
        $dataCommentMe  =   array(
                                'uid'           =>  $info['cUid'],
                                'cUid'          =>  $info['uid'],
                                'cNickname'     =>  $info['nickname'],
                                'rUid'          =>  $info['rUid'],
                                'rNickname'     =>  $info['rNickname'],
                                'bodyId'        =>  $info['bodyId'],
                                'parentId'      =>  $info['parentId'],
                                'type'          =>  $info['type'],
                                'content'       =>  $info['content'],
                                'commentType'   =>  $this->commentMeType,
                                'time'          =>  AC::SERVER_TIME,
                                'replyTime'     =>  AC::SERVER_TIME,
                            );
        $commentMeKey   =   $this->commentKeyPrefix. $info['cUid'];
        $commentMeResult=   Storage::addData($commentMeKey, $dataCommentMe);
        if (empty($commentMeResult))
        {
            AC::$errorNo    =   'CIM004';
            return  FALSE;
        }
        if (!empty($info['parentId']))
        {
            $replyInfo['replyNum']  =   $oneComment['replyNum'];
            $this->countReply($replyInfo);
        }/*}}}*/
        $dataCommentMe['id'] = $commentMeResult;
        return  $dataCommentMe;
    }/*}}}*/

    public function removeComment($info)/*{{{*/
    {
        if (empty($info['uid']) ||  empty($info['id']))
        {
            AC::$errorNo    =   'CIM005';
            return  FALSE;
        }

        $oneComment =   $this->getOneComment($info);
        if (empty($oneComment['uid']))
        {
            AC::$errorNo    =   'CIM013';
            return  FALSE;
        }
        $removeInfo =   array('uid' =>  $info['uid']);
        if (($oneComment['commentType'] ==  $this->commentMeType))
        {
            $removeInfo['bodyId']       =   $oneComment['bodyId'];
            $removeInfo['commentTimes'] =   -1;
        }

        $key    =   $this->commentKeyPrefix. $info['uid'];
        $where  =   array('id' => $info['id']);
        $result =   Storage::delConditionData($key, $where);

        if (empty($result)) return  $result;
        return  $removeInfo;
    }/*}}}*/
    
    # 批量删除  $info['cUid']=要删除的用户    /*{{{*/
    public function removeManyComment($info)
    {
        if (empty($info['uid']) || empty($info['bodyId']) || empty($info['cUid']))
        {
            AC::$errorNo    =    'CIM005';
            return FALSE;
        }
        
        $result     =   $this->getAllComment($info);
        $key            =   $this->commentKeyPrefix. $info['uid'];
        
        $replywhere     =   array('bodyId'=> $info['bodyId'],'rUid'=> $info['cUid']);
        $replyreuslt    =   Storage::delConditionData($key, $replywhere);
        
        $commentwhere   =   array('bodyId'=> $info['bodyId'],'cUid'=> $info['cUid']);
        $commentresult  =   Storage::delConditionData($key, $commentwhere);
        
        if ($result != 0)
        {
            $removeInfo     =   array('uid'=> $info['uid'],'bodyId'=> $info['bodyId'],'commentTimes'=> '-'.$result);
        }
        else 
        {
            $removeInfo     =   array('uid'=> $info['uid'],'bodyId'=> $info['bodyId']);
        }
        
        return $removeInfo;
    }/*}}}*/
    
    # 获取所有评论      /*{{{*/
    public function getAllComment($info)
    {
        if (empty($info['uid']) ||  empty($info['bodyId']))
        {
            AC::$errorNo    =   'CIM011';
            return  FALSE;
        }
        
        $key    =   $this->commentKeyPrefix. $info['uid'];
        $where  =   array('bodyId' => $info['bodyId'],'uid'=> $info['uid'],'cUid'=> $info['cUid'],'commentType'=> 1);
        $result =   Storage::countDataRow($key, $where);
        
        return  $result;
    }/*}}}*/
    
    public function getCommentReplyList($info)/*{{{*/
    {
        if (empty($info['uid']) ||  empty($info['bodyId'])  ||  empty($info['type'])    ||  empty($info['parentId']))
        {
            AC::$errorNo    =   'CIM010';
            return  FALSE;
        }

        $start  =   0;
        $length =   AC::COMMENT_REPLY_LIST_LEN;
        isset($info['start'])   &&  $start  =   $info['start'];
        isset($info['length'])  &&  $length =   $info['length'];
        if ($start  <   0)  $start  =   0;

        $key    =   $this->commentKeyPrefix. $info['uid'].$this->slaveKey;
        $where  =   array('bodyId'  =>  $info['bodyId'], 'type' => $info['type'], 'commentType' => $this->commentMeType, 'parentId' => $info['parentId']);
        if (!empty($info['id']))    $where  =   ' id > '. $info['id']. ' AND bodyId = '. $info['bodyId']. ' AND `commentType` = '. $this->commentMeType. ' AND parentId = '. $info['parentId'];
        $orderBy=   ' id ASC ';
        $result =   Storage::getConditionManyData($key, $where, $orderBy, $start, $length);

        return  $result;
    }/*}}}*/
    public function getCommentReplyListUp($info)/*{{{*/
    {
        if (empty($info['uid']) ||  empty($info['bodyId'])  ||  empty($info['type'])    ||  empty($info['parentId']))
        {
            AC::$errorNo    =   'CIM010';
            return  FALSE;
        }
        if (empty($info['id'])) return  $this->getCommentReplyList($info);

        $start  =   0;
        $length =   AC::COMMENT_LIST_DISPLAY_LEN;
        isset($info['start'])   &&  $start  =   $info['start'];
        isset($info['length'])  &&  $length =   $info['length'];
        if ($start  <   0)  $start  =   0;

        $key    =   $this->commentKeyPrefix. $info['uid'].$this->slaveKey;
        $where  =   ' id > '. $info['id']. ' AND bodyId = '. $info['bodyId']. ' AND `commentType` = '. $this->commentMeType. ' AND parentId = '. $info['parentId'];
        $orderBy=   ' id ASC ';
        $result =   Storage::getConditionManyData($key, $where, $orderBy, $start, $length);

        return  $result;
    }/*}}}*/
    public function getCommentReplyListDown($info)/*{{{*/
    {
        if (empty($info['uid']) ||  empty($info['bodyId'])  ||  empty($info['type'])    ||  empty($info['parentId']))
        {
            AC::$errorNo    =   'CIM010';
            return  FALSE;
        }
        if (empty($info['id'])) return  $this->getCommentReplyList($info);

        $start  =   0;
        $length =   AC::COMMENT_REPLY_LIST_LEN;
        isset($info['start'])   &&  $start  =   $info['start'];
        isset($info['length'])  &&  $length =   $info['length'];
        if ($start  <   0)  $start  =   0;

        $key    =   $this->commentKeyPrefix. $info['uid'].$this->slaveKey;
        $where  =   ' id > '. $info['id']. ' AND bodyId = '. $info['bodyId']. ' AND `commentType` = '. $this->commentMeType. ' AND parentId = '. $info['parentId'];
        $orderBy=   ' id ASC ';
        $result =   Storage::getConditionManyData($key, $where, $orderBy, $start, $length);

        return  $result;
    }/*}}}*/

    private function countReply($info)/*{{{*/
    {
        if (empty($info['uid']) ||  empty($info['id']))
        {
            AC::$errorNo    =   'CIM011';
            return  FALSE;
        }
        $key    =   $this->commentKeyPrefix. $info['uid'];
        $data   =   array('replyTime'  =>  AC::SERVER_TIME, 'replyNum' =>  $info['replyNum'] + 1 );
        $where  =   array('id' => $info['id']);
        $result =   Storage::setConditionData($key, $data, $where);

        return  $result;
    }/*}}}*/

    public function getOneComment($info)/*{{{*/
    {
        if (empty($info['uid']) ||  empty($info['id']))
        {
            AC::$errorNo    =   'CIM011';
            return  FALSE;
        }

        $key    =   $this->commentKeyPrefix. $info['uid'];
        $where  =   array('id' => $info['id']);
        $result =   Storage::getConditionData($key, $where);

        return  $result;
    }/*}}}*/

    public function countCommentPeople($xdIndex)/*{{{*/
    {
        if (is_null($xdIndex))  return  FALSE;

        $insertSql  =   '
            INSERT IGNORE INTO xxtComment.commentPeople (bodyId, num, tableIndex) 
            SELECT tmp.bodyId, count(*) AS num, '. $xdIndex. ' FROM
            (
                SELECT bodyId, cUid FROM xxtComment.commentInfo_'. $xdIndex. ' WHERE type=1 AND commentType=1 GROUP BY bodyId, cUid
            )   AS tmp GROUP BY bodyId
            ';
        $keyClient  =   $this->commentKeyPrefix. $xdIndex;
        $result     =   Storage::execDbSentenceByClient($keyClient, $insertSql);
        return  $result;
    }/*}}}*/
    
    /**
     * 获取点滴评论列表
     * @param unknown $uid
     * @param unknown $bodyId
     * @param number $parentId
     * @param number $id
     * @param number $start
     * @param unknown $length
     * @return boolean|Ambigous <unknown, boolean, multitype:>
     */
    public function getDiaryCommentList ($uid, $bodyId, $id = 0, $start = 0, $length = AC::COMMENT_LIST_DISPLAY_LEN) {
        if (empty($uid) || empty($bodyId)) {
            AC::$errorNo    =   'CIM006';
            return  FALSE;
        }
        
        $where  =   array('bodyId'  =>  $bodyId, 'type' => 1, 'commentType' => $this->commentMeType);
        if ($id)    $where  =   ' id > '. $id. ' AND bodyId = '. $bodyId. ' AND `commentType` = '. $this->commentMeType;

        $key    =   $this->commentKeyPrefix. $uid.$this->slaveKey;
        $orderBy=   ' id ASC ';
        if ($parentId) $orderBy=   ' id ASC ';
        
        $result =   Storage::getConditionManyData($key, $where, $orderBy, $start, $length);
        
        return  $result;
    }
    
    /**
     * 就评论数据
     * @param unknown $param
     * @return Ambigous
     */
    public function assembleOldDataOfComment ($param) {
        $comment = array(
            "id"            => "0",
            "uid"           => "0",
            "cUid"          => "0",
            "cNickname"     => "",
            "rUid"          => "0",
            "rNickname"     => "",
            "parentId"      => "0",
            "parentUid"     => "0",
            "parentContent" => "",
            "bodyId"        => "0",
            "comment_id"    => "0",
            "type"          => "1",
            "content"       => "",
            "commentType"   => "1",
            "time"          => AC::SERVER_TIME,
            "replyTime"     => AC::SERVER_TIME,
            "replyNum"      => "0",
            "status"        => "0",
            "replyList"     => array(),
            "avatar"        => "",
            "user"          => (Object) array()
        );
    
        // 组装返回数据(不需要特殊处理,直接返回替换字段后的数据)
        $this->getDefaultCommentData($param, $comment);
    
        // 获取二级回复列表
        $comment['replyList'] = $this->getDiaryCommentList($comment['uid'], $comment['bodyId'], $comment['id'], $comment['id']);
        $this->getDefaultCommentData($comment['replyList'], $comment['replyList']);
    
        // 获取用户信息
        $userInfo = $this->autoUidModel->getUserInfo($comment['cUid']);
        $comment['avatar'] = $userInfo['avatar'];
        $comment['user']   = $userInfo;
        $comment['user']['nickname']  =  $this->autoUidModel->getRemarkName($comment['user']);
    
        return $comment;
    }
    
    /**
     * 处理参数
     * @param unknown $param
     * @param unknown $comment
     */
    private function getDefaultCommentData ($param, $comment) {
        UK::assembleReplacedFieldData($param, $comment, array(
            "id"            => "id",
            "uid"           => "uid",
            "cUid"          => "cUid",
            "cNickname"     => "cNickname",
            "rUid"          => "rUid",
            "rNickname"     => "rNickname",
            "parentId"      => "parentId",
            "parentUid"     => "parentUid",
            "parentContent" => "parentContent",
            "bodyId"        => "bodyId",
            "comment_id"    => "comment_id",
            "type"          => "type",
            "content"       => "content",
            "commentType"   => "commentType",
            "time"          => "time",
            "replyTime"     => "replyTime",
            "replyNum"      => "replyNum",
            "status"        => "status"
        ));
    }
    
    /**
     * 获取点滴评论列表
     * @param unknown $param
     * @return StdClass|multitype:number unknown
     */
    public function getCommentsOfDrabs ($param, $time, $ishot = null) {
        $comments = $this->loopDatasOfComments($param, $time, $ishot);
        if (empty($comments)) {
            return (Object) array();
        }
    
        return array('comments' => $comments, 'counts' => count($comments));
    }
    
    /**
     * 循环列表数据
     * @param unknown $param
     * @return multitype:|multitype:multitype:multitype:
     */
    private function loopDatasOfComments ($param, $time, $ishot = null) {
        if (empty($param)) return array();
    
        $result = array();
        $arrSort = [];
        foreach ($param as $key => $value) {
            $tmp = $this->assembleDataOfComment($value, array(), $time);
            if (empty($tmp['id']) || empty($tmp['uid'])) continue;
            if($this->diaryListCacheModel->isUidRemoving($tmp['uid'])) continue;
            if ($ishot){
                if(!$tmp['weight']) continue;
                $arrSort[] = $tmp['weight'];
                $this->diaryListCacheModel->addHotComment($tmp['tid'], $tmp['weight'], $tmp['id']);
            } 
            
            $result[] = $tmp;
        }
        if ($ishot && !empty($arrSort)){
            array_multisort($arrSort, SORT_DESC, $result);    
        }

        return $result;
    }
    
    /**
     * 组装数据结构
     * @param unknown $param
     * @param unknown $emotionIdsOfMine
     * @return Ambigous
     */
    public function assembleDataOfComment ($param, $emotionIdsOfMine = array(), $time = 0) {

        $comment = array(
            "id"            => "0",
            "tid"           => "0",
            "uid"           => "0",
            "nickname"      => "",
            "author_uid"    => "0",
            "author_name"   => "",
            "rUid"          => "0",
            "rNickname"     => "",
            "gid"           => "0",
            "type"          => "0",
            "parentId"      => "0",
            "position"      => "0",
            "content"       => "",
            "status"        => "0",
            "extra"         => "",
            "is_favor"      => "0",
            "favorites"     => "0",
            "response_num"  => "0",
            "weight"        => "0",
            "time"          => AC::SERVER_TIME,
            "attachments"   => array(),
            "voiceList"     => array(),
            "imageList"     => array(),
            "url_struct"    => array(),
            "quote"         => (Object) array(),
            "childComment"  => (Object) array(),
            "user"          => (Object) array()
        );
        
        if (isset($param['extra']) && UK::isJSON($param['extra'])) {
            $extra   = json_decode($param['extra'], true);
            $keys    = array_keys($comment);
            $key_num = count($keys);
            
            for ($i = 0; $i < $key_num; $i++) {
                if (isset($extra[$keys[$i]]) && $extra[$keys[$i]]) {
                    $comment[$keys[$i]] = $extra[$keys[$i]];
                }
            }
            
            if ($time < AC::$diaryCommentCf['transfer_time']) $comment['position'] = '0';
            $comment['id'] = $param['id'];
            if ($comment['user']['uid']) {
                $comment['user'] = $this->autoUidModel->getUserInfo($comment['user']['uid']);
            }
            return $comment;
        }
        
        if ($time < AC::$diaryCommentCf['transfer_time'] && empty($param['tid'])) {
            UK::assembleReplacedFieldData($param, $comment, array(
                "id"            => "id",
                "uid"           => "author_uid",
                "cUid"          => "uid",
                "cNickname"     => "nickname",
                "rUid"          => "rUid",
                "rNickname"     => "rNickname",
                "type"          => "type",
                "parentId"      => "parentId",
                "content"       => "content",
                "status"        => "status",
                "replyNum"      => "response_num",
                "time"          => "time"
            ));
        }else{
            UK::assembleReplacedFieldData($param, $comment, array(
                "tid"           => "tid",
                "uid"           => "uid",
                "nickname"      => "nickname",
                "author_uid"    => "author_uid",
                "author_name"   => "author_name",
                "rUid"          => "rUid",
                "rNickname"     => "rNickname",
                "gid"           => "gid",
                "type"          => "type",
                "parentId"      => "parentId",
                "position"      => "position",
                "content"       => "content",
                "status"        => "status",
                "favorites"     => "favorites",
                "response_num"  => "response_num",
                "time"          => "time"
            ));
        }

        if ($comment['status'] > 0) $comment['content'] = '该评论已被删除';
        if ($comment['tid'] > 0 && $comment['position'] > 0) {
            $comment['id'] = $comment['position'];
            $favor = $this->topicModel->getFavoriteTopicInfo(array('uid' => AC::HOST_UID, 'tid' => $comment['tid'], 'position' => $comment['position']));
            if (!empty($favor) && $favor['status'] == 0) {
                $comment['is_favor'] = '1';
            }

            // 获取附件
            list($comment['attachments'], $comment['voiceList']) = $this->getAttachmentsOfComment($param);

            // 获取引用结构
            if ($time >= AC::$diaryCommentCf['transfer_time'] && $comment['parentId'] > 0) {
                $comment['quote'] = $this->getQuoteOfComment($param['extend']);
            }
            if ($time >= AC::$diaryCommentCf['transfer_time']) {
                $comment['childComment'] = $this->childCommentModel->getCommentOfComment($param['extend']);
            }
        }
        
        // 获取我所买的表情
        if (empty($emotionIdsOfMine)) {
            $emotionIdsOfMine = $this->getEmotionIdsOfMine($param['extend'], $param['time']);
        }

        // 返回表情组装数据
        $comment['imageList']  = Emotion::emotionToImgList($comment['content'], $emotionIdsOfMine);

        // 获取活动数据
        $comment['url_struct'] = $this->getUrlStruct($param['url_struct']);
        $comment['content']   = Emotion::emotionToMark($comment['content'], $emotionIdsOfMine);

        // 获取评论相关用户备注信息
        $comment = $this->getRemarksOfRelativeUser($comment);
        //获取评论的权重值
        if (isset($comment['childComment']) && is_array($comment['childComment'])) {
            $response_num = count($comment['childComment']['commentList']) + $comment['childComment']['counts'];
        }else{
            $response_num = $comment['response_num'];
        }
        $comment['weight'] = $this->getWeightOfComment($comment['content'], $response_num, $comment['favorites'], $comment['user']['is_vip'], $comment['user']['is_ability'], $comment['user']['ability_level'], $comment['user']['level']);
        
        if ($time < AC::$diaryCommentCf['transfer_time']) $comment['position'] = '0';
        return $comment;
    }

    /**
     * 获取点滴单个评论的权重
     * @param 字数    $content
     * @param 回复数  $replys
     * @param 点赞数  $likes
     * @param 是否会员  $isVip
     * @param 是否达人  $isAbility
     * @param 达人等级  $verified
     * @param 用户等级  $level
     * @return weight:int  权重
     */
    private function getWeightOfComment ($content, $replys, $likes, $isVip, $isAbility, $verified, $level) {
        $weight = 0;
        $words = strlen($content);
        if($words < 15 && $replys == 0 && $likes == 0 && $level < 10 && $isVip == 0) return $weight;

        $n = $z = 0;
        if($words < 15) $n = 0;
        elseif($words >= 15 && $words < 45) $n = 5;
        elseif($words >= 45) $n = 10;
        
        if($level >= 10 && $level <= 20) $z = 1;
        elseif($level > 20 && $level <= 40) $z = 1.5;
        elseif($level > 40 && $level <= 60) $z = 2;
        elseif($level > 60 && $level <= 80) $z = 2.5;
        elseif($level > 80 && $level <= 100) $z = 3;
        if(!$isAbility) {
            $verified = 0;
        }
        $weight = 10*$n + 5*$replys + 5*$likes + 3*$isVip + 4*$verified + 3*$z;
        return $weight;
    }

    /**
     * 获取点滴单个评论的附件
     * @param unknown $param
     * @return multitype:multitype: multitype:multitype:string
     */
    private function getAttachmentsOfComment ($param) {
        $attachmentList = $voiceList = array();
        $tmp = array('uid' => $param['author_uid'], 'tid' => $param['tid'], 'pid' => $param['position']);
    
        // 获取附件信息
        if ($param['attachment'] > 0 && $param['status'] == 0) {
            $attachment     = $this->attachmentModel->getAttachmentInfo($tmp);
            $attachmentList = $attachment['attachmentList'];
            $voiceList      = $attachment['voiceList'];
        }
    
        return array($attachmentList, $voiceList);
    }
    
    private function extendDataOfExtras ($info) {
        $extend = array();
        if ($info){
            $extend     = json_decode($info, TRUE);
        }
    
        return $extend;
    }
    
    /**
     * 获取用户所购买的表情列表
     * @param unknown $extend
     * @param unknown $time
     * @return Ambigous <multitype:, mixed, multitype:number >
     */
    private function getEmotionIdsOfMine ($extend, $time) {
        $emotion_ids_mebuy = array();
        $extend_arr = $this->extendDataOfExtras($extend);
        if ($extend_arr['shop_ids_mebuy']){
            $emotion_ids_mebuy = $extend_arr['shop_ids_mebuy'];
        }
    
        if (empty($emotion_ids_mebuy) && $time < Emotion::$filter_emotion_update_time){
            $emotion_ids_mebuy = Emotion::$default_emotion_ids;
        }
    
        return $emotion_ids_mebuy;
    }
    
    /**
     * 获取活动信息
     * @param unknown $url_struct
     * @return multitype:multitype:string multitype: unknown
     */
    private function getUrlStruct ($url_struct) {
        $result = array();
        // 活动跳转数据组装
        if($url_struct){
            $data_url_struct = array(
                'url_title'    =>    '',
                'url_content'  =>    '',
                'url_image'    =>    '',
                'url_action'   =>    '',
                'url_extend'   =>    array()
            );
    
            $url_struct = json_decode($url_struct, true);
            isset($url_struct['url_title'])      &&    $data_url_struct['url_title']      =    strval($url_struct['url_title']);
            isset($url_struct['url_content'])    &&    $data_url_struct['url_content']    =    strval($url_struct['url_content']);
            isset($url_struct['url_image'])      &&    $data_url_struct['url_image']      =    strval($url_struct['url_image']);
            isset($url_struct['url_action'])     &&    $data_url_struct['url_action']     =    strval($url_struct['url_action']);
            isset($url_struct['url_extend'])     &&    $data_url_struct['url_extend']     =    $url_struct['url_extend'];
            $result[] = $data_url_struct;
        }
    
        return $result;
    }
    
    /**
     * 获取备注名信息
     * @param unknown $param
     * @return Ambigous <unknown, Ambigous>
     */
    private function getRemarksOfRelativeUser ($param) {
        // 获取评论用户信息
        $param['user']  = $this->autoUidModel->getUserInfo($param['uid']);
        $user_author    = $this->autoUidModel->getUserInfo($param['author_uid']);
         
        $param['author_name']       =   $this->autoUidModel->getRemarkName(array('uid'=>$param['author_uid'],'nickname'=>$user_author['nickname']));
        $param['nickname']          =   $this->autoUidModel->getRemarkName(array('uid'=>$param['uid'],'nickname'=>$param['user']['nickname']));
        $param['user']['nickname']  =   $param['nickname'];
    
        if ($param['rUid'] && !empty($param['rNickname'])){
            $user_reply			    =   $this->autoUidModel->getUserInfo($param['rUid']);
            $param['rNickname']     =   $this->autoUidModel->getRemarkName(array('uid' => $param['rUid'], 'nickname' => $user_reply['nickname']));
        }
    
        return $param;
    }
    

    private function getQuoteOfComment ($extend) {
        $extend_arr = $this->extendDataOfExtras($extend);
    
        $result = array();
        if ($extend_arr['parentComment']){
            $comment = $extend_arr['parentComment'];
    
            $result = array(
                "rUid"      => strval($comment['uid']),
                "parentId"  => strval($comment['position']),
                "content"   => Emotion::emotionToCharacter($comment['content']),
                "time"      => strval($comment['time']),
                "user"      => $this->autoUidModel->getUserInfo($comment['uid'])
            );
        }
        
        $result = $result ? $result : (Object) array();
        return $result;
    }
    
    /**
     * 添加评论
     * @param unknown $info
     * @param string $function
     * @return boolean|Ambigous
     */
    public function addComment ($info) {
        $data = $this->checkCommentPassedArg($info);
        if (empty($data) || AC::$errorNo) {
            return false;
        }
        
        $this->meComment($data);
        $this->commentRuser($data);
        $result = $this->commentDiary($data);
        
        return $result;
    }
    
    /**
     * 检查传入参数
     * @param unknown $info
     * @return boolean|unknown
     */
    private function checkCommentPassedArg($info) {
        $info['content']    = UK::getstr($info['content'], AC::COMMECT_DATA_NUMBERS);
        $info['nickname']   = UK::getstr($info['nickname'], 24,'',1);
        $info['cNickname']  = UK::getstr($info['cNickname'], 24,'',1);
         
        if (empty($info['uid']) ||  strlen($info['nickname']) < 1||  empty($info['cUid'])    ||  strlen($info['cNickname']) <1) {
            AC::$errorNo    =   'CIM001';
            return  FALSE;
        }
        
        if (empty($info['type']) ||  empty($info['bodyId']) || strlen($info['content']) < 1) {
            AC::$errorNo    =   'CIM002';
            return  FALSE;
        }
        
        if (AC::FEED_COMMENT == $info['type']) {
            AC::$errorNo    =   'CIM009';
            return  FALSE;
        }
        
        if (intval($info['parentId']) > 0) {
            $replyInfo      =   array('uid' => $info['cUid'], 'id' => $info['parentId']);
            $oneComment     =   $this->getOneComment($replyInfo);
            if (empty($oneComment['uid'])) {
                AC::$errorNo=   'CIM012';
                return  FALSE;
            }
        }
        
        return $info;
    }
    
    /**
     * 用于我的评论
     * @param unknown $info
     * @return Ambigous <unknown, boolean, number, resource>
     */
    private function meComment ($info) {
        $data  =   array(
            'uid'           =>  $info['uid'],
            'cUid'          =>  $info['cUid'],
            'cNickname'     =>  $info['cNickname'],
            'rUid'          =>  $info['rUid'],
            'rNickname'     =>  $info['rNickname'],
            'bodyId'        =>  $info['bodyId'],
            'parentId'      =>  $info['parentId'],
            'type'          =>  $info['type'],
            'content'       =>  $info['content'],
            'commentType'   =>  $this->meCommentType,
            'time'          =>  AC::SERVER_TIME,
            'replyTime'     =>  AC::SERVER_TIME,
            'extra'         =>  $info['extra'] ? $info['extra'] : ''
        );
        $key   =   $this->commentKeyPrefix. $info['uid'];
        $result=   Storage::addData($key, $data);

        return $result;
    }
    
    /**
     * 评论上一级评论
     * @param unknown $info
     * @return Ambigous <number, unknown, boolean, resource>
     */
    private function commentRuser ($info) {
        $result = 0;
        if (intval($info['rUid']) > 0 && $info['cUid'] != $info['rUid']){
            $data  =   array(
                'uid'           =>  $info['rUid'],
                'cUid'          =>  $info['uid'],
                'cNickname'     =>  $info['nickname'],
                'rUid'          =>  $info['rUid'],
                'rNickname'     =>  $info['rNickname'],
                'bodyId'        =>  $info['bodyId'],
                'parentId'      =>  $info['parentId'],
                'type'          =>  $info['type'],
                'content'       =>  $info['content'],
                'commentType'   =>  $this->userCommentMeType,
                'time'          =>  AC::SERVER_TIME,
                'replyTime'     =>  AC::SERVER_TIME,
                'extra'         =>  $info['extra'] ? $info['extra'] : ''
            );
            $key   =   $this->commentKeyPrefix. $info['rUid'];
            $result=   Storage::addData($key, $data);
        }
        
        return $result;
    }
    
    /**
     * 评论日记
     * @param unknown $info
     * @return Ambigous <unknown, boolean, number, resource>
     */
    private function commentDiary ($info) {
        $data  =   array(
            'uid'           =>  $info['cUid'],
            'cUid'          =>  $info['uid'],
            'cNickname'     =>  $info['nickname'],
            'rUid'          =>  $info['rUid'],
            'rNickname'     =>  $info['rNickname'],
            'bodyId'        =>  $info['bodyId'],
            'parentId'      =>  $info['parentId'],
            'type'          =>  $info['type'],
            'content'       =>  $info['content'],
            'commentType'   =>  $this->commentMeType,
            'time'          =>  AC::SERVER_TIME,
            'replyTime'     =>  AC::SERVER_TIME,
            'extra'         =>  $info['extra'] ? $info['extra'] : ''
        );
        $key   =   $this->commentKeyPrefix. $info['cUid'];
        $result=   Storage::addData($key, $data);

        return $result;
    }
}

